package com.xyy.saas.payment.controller;

import com.xyy.saas.payment.cores.enums.ResultCodeEnum;
import com.xyy.saas.payment.cores.vo.ResultVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * 统一异常处理
 * @author dake
 * @date 20200327
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResultVO<String> handle(HttpServletRequest request, MethodArgumentNotValidException me) {
        LOGGER.error("{} catch Exception e: ", request.getRequestURI(), me);
        return ResultVO.createParamError(Optional.ofNullable(me.getBindingResult().getAllErrors().get(0).getDefaultMessage()).orElse(ResultCodeEnum.PARAM_ERROR.getDisplayMsg()));
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResultVO<String> handle(HttpServletRequest request, Exception e) {
        LOGGER.error("{} catch Exception e: ", request.getRequestURI(), e);
        return ResultVO.createError(e.getMessage());
    }
}
